package com.ruoyi.framework.security.filter;

import com.ruoyi.common.core.domain.model.CustomDefaultOidcUser;
import com.ruoyi.common.core.domain.model.CustomJwtAuthenticationToken;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        Authentication authentication = SecurityUtils.getAuthentication();
        if (StringUtils.isNotNull(loginUser)){
            tokenService.verifyToken(loginUser);
            if (StringUtils.isNull(authentication)){
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            } else if (authentication instanceof OAuth2AuthenticationToken oauth2Token) {
                DefaultOidcUser oidcUser = (DefaultOidcUser) authentication.getPrincipal();
                CustomDefaultOidcUser customDefaultOidcUser = new CustomDefaultOidcUser(oidcUser.getAuthorities(), oidcUser.getIdToken());
                customDefaultOidcUser.setLoginUser(loginUser);
                OAuth2AuthenticationToken newAuth = new OAuth2AuthenticationToken(
                        customDefaultOidcUser,
                        oauth2Token.getAuthorities(),
                        oauth2Token.getAuthorizedClientRegistrationId()
                );
                SecurityContextHolder.getContext().setAuthentication(newAuth);
            } else if (authentication instanceof JwtAuthenticationToken jwtToken) {
                CustomJwtAuthenticationToken customJwtAuthenticationToken = new CustomJwtAuthenticationToken(jwtToken.getToken());
                customJwtAuthenticationToken.setLoginUser(loginUser);
                SecurityContextHolder.getContext().setAuthentication(customJwtAuthenticationToken);
            }
        }
        chain.doFilter(request, response);
    }
}
